//
//  MBDGroupSearchViewController.swift
//  MasterBoy
//
//  Created by kyson on 2023/4/8.
//

import Foundation
import YYText
import UIKit


class MBDGroupSearchViewController : MBDBaseViewController {
    var tableView : UITableView!
    var viewModel : MBDGroupSearchViewModel!
    
    var searchBar : UISearchBar!

    override func viewDidLoad() {
        super.viewDidLoad()
        viewModel = MBDGroupSearchViewModel()
        
        //高度默认就是 42，设置成其他高度也不生效
        searchBar = UISearchBar(frame: CGRectMake(0, 3, UIScreen.main.bounds.width - 120, 21))
        if #available(iOS 13.0, *) {
            searchBar.searchTextField.font = UIFont.systemFont(ofSize: 14)
            searchBar.searchTextField.layer.cornerRadius = 21 // I've tried other numbers besides this too with no luck
            
            searchBar.searchTextField.clipsToBounds = true

        } else {
            // Fallback on earlier versions
        }
                
        searchBar.tintColor = UIColor(colorHex: 0x4273d0)
        searchBar.returnKeyType = .search; //设置按键类型
        searchBar.delegate = self
        //左边的 icon 往右边动一动
        searchBar.setPositionAdjustment(UIOffset(horizontal: 10, vertical: 0), for: .search)
        
        self.navigationItem.titleView = searchBar
        
        tableView = UITableView()
        
        tableView.translatesAutoresizingMaskIntoConstraints = false
        self.view.addSubview(tableView)
        
        NSLayoutConstraint.activate([
        self.view.safeAreaLayoutGuide.topAnchor.constraint(equalTo: tableView.topAnchor),
                    self.view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
                    self.view.leadingAnchor.constraint(equalTo: tableView.leadingAnchor),
                    self.view.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
                ])
        tableView.backgroundColor = UIColor(colorHex: 0xF4F4F4)
        tableView.showsVerticalScrollIndicator = false
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.dataSource = self
        tableView.delegate = self
        tableView.rowHeight = 85
        
        tableView.register(MBDGroupSearchResultCell.self, forCellReuseIdentifier: "MBDGroupSearchResultCell")
        tableView.register(MBDGroupSearchTitleCell.self, forCellReuseIdentifier: "MBDGroupSearchTitleCell")
        
        tableView.setDynamicBackgroundColor()
        view.setDynamicBackgroundColor()
    }
    
    override func updateColors() {
        super.updateColors()
        tableView.setDynamicBackgroundColor()
        tableView.reloadData()
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.searchBar.becomeFirstResponder()
    }
}


extension MBDGroupSearchViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.viewModel.cellModels?.count ?? 0
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellModel = self.viewModel.cellModels![indexPath.row]

        if cellModel is MBDGroupSearchTitleCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupSearchTitleCell", for: indexPath)
            (cell as! MBDGroupSearchTitleCell).cellModel = cellModel
            return cell
        }
        
        if cellModel is MBDGroupSearchResultCellModel {
            let cell = tableView.dequeueReusableCell(withIdentifier: "MBDGroupSearchResultCell", for: indexPath)
            (cell as! MBDGroupSearchResultCell).cellModel = cellModel
            return cell
        }
        
        return UITableViewCell()
    }
}


extension MBDGroupSearchViewController : UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDGroupSearchResultCellModel
        let viewModel = MBDGroupDetailViewModel(groupDetail: realCellModel.group!)
        let vc = MBDGroupDetailViewController(viewModel: viewModel)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let cellModel = self.viewModel.cellModels![indexPath.row]
        let realCellModel = cellModel as! MBDCommonCellModel
        return realCellModel.cellHeight()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        self.searchBar.resignFirstResponder()
    }
}

extension MBDGroupSearchViewController: UISearchBarDelegate {
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//        self.viewModel.generateTestData()
        self.viewModel.doRequest(kw: searchText) {error, result, total in
            self.viewModel.cellModels = result
            self.tableView.reloadData()

        }
    }
}


class MBDGroupSearchResultCell: MBDCommonCell {

    private var titleLabel : YYLabel!
    private var subtitleLabel : YYLabel!
    private var logoImageView : UIImageView!
    private var logoLabel :YYLabel!

    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initialize()
    }
    
    override var cellModel: Any! {
        didSet {
            let realCellModel = cellModel as! MBDGroupSearchResultCellModel
            
            self.title = realCellModel.group?.groupName
            
            self.subtitle = realCellModel.group?.groupDesc
            
            let logoString : Substring = self.title?.prefix(1) ?? "群"
            self.logoLabel.text = String(logoString.uppercased())
        }
    }

    func initialize() {
        self.contentView.setDynamicForgroundColor()
        self.commonBackgroundView.setDynamicForgroundColor()


        logoImageView = UIImageView(image: UIImage(named: "item_thumb"))
        logoImageView = UIImageView()
        logoImageView.backgroundColor = UIColor(colorHex: 0x4273d0)
        
        logoLabel = YYLabel()
        logoLabel.textColor = UIColor.white
        logoLabel.font = UIFont.boldSystemFont(ofSize: 36)
        logoLabel.textAlignment = .center
        logoImageView.addSubview(logoLabel)
        
        logoImageView.layer.cornerRadius = 30
        logoImageView.clipsToBounds = true
        self.contentView.addSubview(logoImageView)
        
        titleLabel = YYLabel()
        self.contentView.addSubview(titleLabel)
        
        subtitleLabel = YYLabel()
        self.contentView.addSubview(subtitleLabel)
        
        logoImageView.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(60, 60))
            make.top.equalTo(15)
            make.left.equalTo(15)
        }
        
        logoLabel.snp.makeConstraints { make in
            make.size.equalTo(CGSizeMake(60, 60))
            make.center.equalTo(logoImageView)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(logoImageView.snp.right).offset(15)
            make.top.equalTo(logoImageView.snp.top)
            make.right.equalTo(self.contentView).offset(-15)
            make.height.equalTo(0)
        }
        
        subtitleLabel.snp.makeConstraints { make in
            make.left.equalTo(logoImageView.snp.right).offset(15)
            make.top.equalTo(titleLabel.snp.bottom).offset(6)
            make.right.equalTo(self.contentView).offset(-15)
            make.height.equalTo(0)
        }
    }
    
    var subtitle:String? {
        didSet {
            let subtitleAttributeString = NSMutableAttributedString(string: self.subtitle ?? "")
            subtitleAttributeString.yy_font = UIFont.systemFont(ofSize: 12)
            subtitleAttributeString.yy_lineSpacing = 4
            subtitleAttributeString.setDynamicTextColor()
            
            let subtitleContainer = YYTextContainer()
            let subtitleWidth = CGRectGetWidth(UIScreen.main.bounds) - 15 - 60 - 15 - 15
            subtitleContainer.size = CGSizeMake(subtitleWidth , CGFLOAT_MAX)
            subtitleContainer.maximumNumberOfRows = 2
            
            let subtitleLayout = YYTextLayout(container: subtitleContainer, text: subtitleAttributeString)
            
            subtitleLabel.textLayout = subtitleLayout
            
            subtitleLabel.snp.updateConstraints { make in
                make.height.equalTo(subtitleLayout!.textBoundingSize.height)
            }
            
        }
    }
    
    var title : String? {
        didSet {
            let titleAttributeString = NSMutableAttributedString(string: self.title ?? "")
            titleAttributeString.yy_font = UIFont.boldSystemFont(ofSize: 16)
            titleAttributeString.setDynamicTextColor()
            
            let titlecontainer = YYTextContainer()
            let titleWidth = CGRectGetWidth(UIScreen.main.bounds) - 15 - 60 - 15 - 15
            titlecontainer.size = CGSizeMake(titleWidth , CGFLOAT_MAX)
            titlecontainer.maximumNumberOfRows = 1
            
            let titleLayout = YYTextLayout(container: titlecontainer, text: titleAttributeString)
            titleLabel.textLayout = titleLayout
            
            titleLabel.snp.updateConstraints { make in
                make.height.equalTo(titleLayout!.textBoundingSize.height)
            }
        }
    }
    
    override func prepareForReuse() {
        super.prepareForReuse()
    }
    
}


class MBDGroupSearchTitleCell : MBDCommonCell {
    private var titleLabel : YYLabel!
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.initialize()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        self.initialize()
    }
    
    override var cellModel: Any! {
        didSet {
            let realCellModel = cellModel as! MBDGroupSearchTitleCellModel
            self.title = realCellModel.title
        }
    }

    func initialize() {
        
        self.contentView.setDynamicForgroundColor()
        self.commonBackgroundView.setDynamicForgroundColor()

        titleLabel = YYLabel()
        self.contentView.addSubview(titleLabel)
        
        titleLabel.snp.makeConstraints { make in
            make.left.equalTo(15)
            make.centerY.equalTo(self.contentView)
            make.height.equalTo(0)
        }
    }
    
    var title : String? {
        didSet {
            let titleAttributeString = NSMutableAttributedString(string: self.title ?? "")
            titleAttributeString.yy_font = UIFont.boldSystemFont(ofSize: 16)
            titleAttributeString.setDynamicTextColor()
            
            let titlecontainer = YYTextContainer()
            let titleWidth = CGRectGetWidth(UIScreen.main.bounds) - 15 - 60 - 15 - 15
            titlecontainer.size = CGSizeMake(titleWidth , CGFLOAT_MAX)
            titlecontainer.maximumNumberOfRows = 1
            
            let titleLayout = YYTextLayout(container: titlecontainer, text: titleAttributeString)
            titleLabel.textLayout = titleLayout
            
            titleLabel.snp.updateConstraints { make in
                make.height.equalTo(titleLayout!.textBoundingSize.height)
            }
        }
    }
}
